﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LeetcodeTest._100._40
{
    /*
     
         35. Search Insert Position
         Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0 

         */
    public class Leetcode35
    {
        public int SearchInsert(int[] nums, int target)
        {
            int lowIndex = 0;
            int highIndex = nums.Length;
            int tempIndex = (highIndex - lowIndex) / 2;
            int tempValue;
            //二分查找
            while (lowIndex < highIndex)
            {
                tempValue = nums[tempIndex];
                if (tempValue < target)
                {
                    if (lowIndex == tempIndex)
                    {
                        lowIndex++;
                        break;
                    }
                    lowIndex = tempIndex;
                    tempIndex = lowIndex + (highIndex - lowIndex) / 2;
                }
                else if (tempValue > target)
                {
                    highIndex = tempIndex;
                    tempIndex = lowIndex + (highIndex - lowIndex) / 2;
                }
                else
                {
                    return tempIndex;
                }
            }

            return lowIndex;
        }
    }
}
